package com.cwx.interfaces.rong360.sample;




import com.alibaba.fastjson.JSONObject;
import com.cwx.interfaces.rong360.request.TianjiRequest;
import com.cwx.interfaces.rong360.utils.RequestUtil;

import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 通过OpenApi访问天机系统的一个简单的样例
 * @see ClientManager
 * @author chenrui
 *
 */
public class TianjiSample {
	
	/**
	 * 为机构分配的appid，通常是7位数字
	 */
	private String appId = "2010327";
	
	/**
	 * 机构的私钥，需要是pkcs8格式的
	 */
	private static String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALg7lYx0GIg13Qvho4qlvtUjp7BbLnKUxDJN6SeMkNHbFE1BOrHTBqjML2mTyfXzUr1hTFytLIjxnWW7fPEfYyPG8QsdW+NapnRPgxGPPCPr6Yv0YUWO4V10A2xT/uBmTQ79q/YzZ0IHnqLqAaQI6TW50isuUa3fDi8mBMLuFKJRAgMBAAECgYAtnyuwZUtx54y+lXivK84u765l4J6G50oSfvKexZNTNGI5o06KnIxIno+bIGrhygiSNxb22DdwDg0BFUWiXDhrRlLxFLZ7nwDeN1idIg8fsiKLsqxIuvnrwY0L1e9lrSr/jDy8JFX0W8nB8NiUiV5GQhH+YlrsYvqlLCyoH/h0AQJBAPTLIiPEvN0QJwrkfSYhAHLmjdXpAUmnamZREl0SVbPCZ7SziJrFDQfkt/r762FZgS9+geAZuLseRIrMYxuaBkECQQDAqrT5B4lXCv8COngJswxb/8L2UxysSPBtcwsX+6znH0xr+A8vs7CQAuTBpb6uXO8StPMbkAuCgNDtwPFgfDgRAkBeemAMygvSjj9jVthudOJFdnJbkvhqQvEv2C5sOX1WSbvY5Ene4hqrZz0S41PvWKoheIQLyCGiJoZxw3yk1IeBAkEAjXSIHJK49kxfgE5XVZ+8wksc5GePFLsUsvcVPQ2OG77yCA9/buF6D7HgLIE5Z6FZ8h0ipKj0mmNjgjv3vIRXUQJBAKlXKNUFi0iSbqfjCQ82RftlOVT5mDPAD6b8iJo8yE5qURuvTilgaZT3FFMOD59/fMF8/ZHb+d2s/fZ4N4CXyQ4=";
	
	/**
	 * 是否是测试环境，测试环境会连接测试环境并打印debug信息
	 */
	private boolean isTestEnv = false;
	
	public void setIsTestEnv(boolean isTestEnv) {
		this.isTestEnv = isTestEnv;
	}
	
	public void setPrivateKey(String privateKey) {
		this.privateKey = privateKey;
	}
	
	public void setAppId(String appId) {
		this.appId = appId;
	}
	
	/**
	 * 请求OpenAPI的数据
	 */
	public JSONObject doOpenApiRequest(String method, Map<String, Object> params) throws Exception {
		String result = RequestUtil.request(method, params, appId, privateKey, isTestEnv);
		if (result == null || result.length() == 0) {
			throw new Exception("Request tianji api " + method + " returns null");
		}
		JSONObject jsonRet = JSONObject.parseObject(result);
		if (jsonRet == null) {
			throw new Exception("Request tianji api " + method + " got a non-json result");
		}
		return jsonRet;
	}
	
	private static String getPrivateKey() throws IOException {
		FileReader reader = new FileReader("private_key.pem");
		char[] chars = new char[65*13 + 16];
		reader.read(chars);
		String privateKey = new String(chars);
		reader.close();
		return privateKey;
	}
	private JSONObject getReportDetail(Map<String, Object> params) throws Exception {
		TianjiSample sample = new TianjiSample();
		String method = "crawler.api.zx.viewReport";
		JSONObject jsonRet = sample.doOpenApiRequest(method, params);
		if (jsonRet == null) {
			throw new Exception("Request tianji collectUser interface got a non-json result");
		}
		return jsonRet;
	}


	    /**
	     * 收集用户信息测试
	     * @throws Exception
	     */
	    public String testCollectUser() throws Exception {
	        TianjiSample sample = new TianjiSample();
	        TianjiRequest collectRequest = new TianjiRequest();
	        sample.setAppId("2010327"); //TODO 设置Appid
			sample.setPrivateKey(TianjiSample.privateKey); // 设置机构私钥，需要机构替换private_key.pem文件
			sample.setIsTestEnv(false); // 设置为请求测试环境
			long a=new Date().getTime(); 
			java.util.Random r=new java.util.Random(100); 
	        collectRequest.putParam("userId", String.valueOf(a)+String.valueOf(r.nextInt()))
	            .putParam("outUniqueId", String.valueOf(a)+String.valueOf(r.nextInt()))
	            .putParam("type", "zx_crawl") // 参见type字段列表
	            .putParam("platform", "web") // 如果是H5接入则设置为web
	            .putParam("returnUrl", "http://shop.98zhengxin.com:10102")
	            .putParam("notifyUrl", "http://shop.98zhengxin.com:10103");
	        JSONObject ret = sample.collectUser(collectRequest.getParams());
	        return String.valueOf(ret);
	    }
	private JSONObject collectUser(Map<String, Object> params) throws Exception {
		TianjiSample sample = new TianjiSample();
		String method = "tianji.api.tianjireport.collectuser";
		JSONObject jsonRet = sample.doOpenApiRequest(method, params);
		if (jsonRet == null) {
			throw new Exception("Request tianji collectUser interface got a non-json result");
		}
		return jsonRet;
	}
//	    /**
//	     * 获取报告详情测试
//	     * @throws Exception
//	     */
//	    public String  testDetail(DataInfo bean) throws Exception {
//	        TianjiSample sample = new TianjiSample();
//	        TianjiRequest detailRequest = new TianjiRequest();
//	        detailRequest.putParam("merchat_id", bean.getPrmOrderId())
//	        .putParam("app_name", "rong360bigapp")
//	        .putParam("app_version", "2.0.0")
//	        .putParam("platform", "web")
//	        .putParam("notice_url",  "http://m.rong360.com/api/notice")
//	        .putParam("login_name",  bean.getPrmLogin())
//	        .putParam("message_code",  "herdrc")
//	        .putParam("userId", bean.getPrmUserid());
//	           // .putParam("test", "测试中英文混合English");
//	           // .putParam("reportType", "file"); // 如果需要下载HTML文件，则设置此参数
//	        JSONObject ret = sample.getReportDetail(detailRequest.getParams());
//	        return String.valueOf(ret);
//	    }    
}
